const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
var xlsx = require('node-xlsx');
const MAX_LIMIT = 100
exports.main = async (event, context) => {
  let databasename = event.databasename
  // 先取出集合记录总数
  const countResult = await db.collection(databasename).count()
  const total = countResult.total
  //计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  console.log(total, batchTimes)
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection(databasename).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }

  let dbdata=(await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })

  //1,定义excel表格名
  let excelname = Math.floor(10000* Math.random())+'test.xlsx'
  //2，定义存储数据的
  let exceldata = [];
  let row = ['设备ID', '设备名称', '领用人', '产家', '存放地', '价格', '购买日期', '供货商']; //表属性
  exceldata.push(row);
  //console.log(dbdata.data)
  for (let item of dbdata.data) {
    let arr = [];
    arr.push(item.deviceid);
    arr.push(item.devicename);
    arr.push(item.deviceuser);
    arr.push(item.manufacturer);
    arr.push(item.place);
    arr.push(item.price);
    arr.push(item.purchasedate);
    arr.push(item.supplier);
    exceldata.push(arr)
  }

  console.log(exceldata)

  //3，把数据保存到excel里
  var buffer = await xlsx.build([{
    name: excelname,
    data: exceldata
  }]);
  //4，把excel文件保存到云存储里
  return await cloud.uploadFile({
    cloudPath: excelname,
    fileContent: buffer, //excel二进制文件
  })


}